package com.guyu.plugin.mybatis.listener;

import cn.hutool.core.util.ObjectUtil;
import com.guyu.common.core.entity.KeyValue;
import com.guyu.plugin.mybatis.entity.BaseDO;
import com.guyu.plugin.mybatis.entity.BaseUserDO;
import com.guyu.plugin.mybatis.helper.MybatisFlexHelper;
import com.mybatisflex.annotation.UpdateListener;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Objects;

@Slf4j
public class BaseDOUpdateListener implements UpdateListener {
    @Override
    public void onUpdate(Object entity) {
        if (entity instanceof BaseDO baseDO) {
            // 更新时间填充(不管为不为空)
            baseDO.setUpdateTime(LocalDateTime.now());
        }
        if (entity instanceof BaseUserDO baseDO) {
            Long updateUserId = baseDO.getUpdateBy();
            String updateUserName = baseDO.getUpdaterName();
            //监听用户信息
            FlexUserListener flexUserListener = MybatisFlexHelper.getUserListener();
            if (Objects.isNull(flexUserListener)) {
                log.warn("自动注入警告 => 用户未登录");
                return;
            }
            KeyValue<Long, String> user = flexUserListener.getUser();
            if (Objects.nonNull(user)) {
                updateUserId = user.getKey();
                updateUserName = user.getValue();
            }
            updateUserId = ObjectUtil.defaultIfNull(updateUserId, 0L);
            updateUserName = ObjectUtil.defaultIfNull(updateUserName, "");

            baseDO.setUpdateBy(updateUserId);
            baseDO.setUpdaterName(updateUserName);
        }
    }
}
